package com.secneo.appshare.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Debug;
import android.util.Log;

import com.secneo.mp.api.util.MD5;

public class Util
{
	public static List<Drawable> assetList = new ArrayList<Drawable>(10);
	public static int hitCount = 0;
	public static boolean checkChinese(String userName)
	{
		boolean flag = false;
		Pattern p = Pattern.compile("[ \\u4e00-\\u9fbb]+");
		Matcher m = p.matcher(userName);
		if (m.find())
		{
			flag = true;
		}
		return flag;
	}
	
	/*
	 * 获取用户安装的软件list
	 */
	public static List<ApplicationInfo> filterUserApps(List<ApplicationInfo> apps)
	{
		if (apps == null || apps.size() == 0)
		{
			return apps;
		}

		List<ApplicationInfo> userApps = new ArrayList<ApplicationInfo>();

		for (int i = 0, size = apps.size(); i < size; i++)
		{
			ApplicationInfo ai = apps.get(i);

			if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
			{
				userApps.add(ai);
			}
		}
		return userApps;
	}

	public static Drawable getDrawableFromAsset(Context ctx, String url) throws IOException
	{
		if(assetList.isEmpty())
		{
			for(int i=0; i<10; i++)
				assetList.add(null);
		}
		String imageName = "icon";
		AssetManager assetManager = ctx.getAssets();
		int index = 1 ;
		try 
		{
			String strInt = url.substring(url.indexOf(":") + 1);
			if(strInt.equals(""))
				index = 8;
			else
				index = Integer.valueOf(strInt);
			
		} catch (Exception e) {
			e.printStackTrace() ;
			index = 8;
		}
		if (index < 10)
			imageName = imageName + "0" + index + ".png";
		else
			imageName = imageName + index + ".png";
		
		if(assetList.get(index-1) == null)
		{
			InputStream istr = assetManager.open(imageName);
			Bitmap bitmap = BitmapFactory.decodeStream(istr);
			assetList.set(index-1, new BitmapDrawable(bitmap));
		}
		return assetList.get(index-1);
	}
	
	public static Drawable getDrawableFromCache(Context ctx, String url) throws IOException
	{
		if(url == null || url.equals(""))
			return null;
		
		String urlPath = "";
		Uri uri = null;
		if(url.contains("http"))
			urlPath = url;
		else
			urlPath = Constants.SERVER_ICON_URL + url;
		
		File cacheFile = ctx.getCacheDir();
		File file = new File(cacheFile, MD5.toMD5(urlPath));
		try
		{
		    if(file.exists())
		    {
		    	hitCount++;
		    	if((hitCount%100) == 0)
		    		Log.d("MyTag", "HitCount = "+hitCount);
		    	uri = Uri.fromFile(file);
		    }
		    else
		    {
		    	Log.d("MyTag", "Down url = "+urlPath);
		        FileOutputStream outStream = new FileOutputStream(file);
		        HttpURLConnection conn = (HttpURLConnection)new URL(urlPath).openConnection();
		        conn.setConnectTimeout(10 * 1000);
		        conn.setRequestMethod("GET");
		        if(conn.getResponseCode()==200)
		        {
		            InputStream inStream = conn.getInputStream();
		            byte[] buffer = new byte[1024];
		            int len = 0;
		            while( (len = inStream.read(buffer)) !=-1 )
		            {
		                outStream.write(buffer, 0, len);
		            }
		            outStream.close();
		            inStream.close();
		            uri = Uri.fromFile(file);
		        }
		        else
		        	return null;
		    }
	    
		} catch (Exception ex) 
		{
			Log.d("MyTag", "getDrawableFromCache error = "+ex.getMessage());
			ex.printStackTrace();
		}
		finally
		{
			if(file.length()<10)
			{
				file.delete();
				return null;
			}
		}
	    return Drawable.createFromStream(ctx.getContentResolver().openInputStream(uri), null);
	}
	
	public static void clearLargeCache(Context ctx) throws IOException
	{
		File cacheFile = ctx.getCacheDir();
		File[] files = cacheFile.listFiles();
		if (dirSize(files) >= 6 * 1024 * 1024)
		{
			Arrays.sort(files, new Comparator<File>()
			{
				@Override
				public int compare(File object1, File object2)
				{
					File file1 = (File) object1;
					File file2 = (File) object2;
					long diff = file1.lastModified() - file2.lastModified();
					if (diff > 0)
						return 1;
					else if (diff == 0)
						return 0;
					else
						return -1;
				}
			});
			
			int count = files.length/2 ;
			for (int i = count; i >= 0; i--)
			{
				if (!files[i].isDirectory())
					files[i].delete();
			}
		}
	}

	/* Return the size of a directory in bytes */
	private static long dirSize(File[] fileList)
	{
		long result = 0;
		for (int i = 0; i < fileList.length; i++)
		{
			if (!fileList[i].isDirectory())
			{
				// Sum the file size in bytes
				result += fileList[i].length();
			}
		}
		Log.d("MyTag", "Cache size(K) =" + result / 1024);
		return result;
	}
	
	private static int logNum = 0;
	public static void logHeap(Class clazz) 
	{
        Double allocated = new Double(Debug.getNativeHeapAllocatedSize())/new Double((1048576));
        Double available = new Double(Debug.getNativeHeapSize()) / (1048576.0f);
        Double free = new Double( (double)Debug.getNativeHeapFreeSize()) / (1048576.0f) ;
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(2);
        df.setMinimumFractionDigits(2);

        Log.e("HeapLog", "debug.count = " + logNum);
        Log.e("HeapLog", "NativeHeapSize = " +df.format(available) + "MB"+ "   NativeHeapAllocatedSize = "+df.format(allocated) + "MB" + "   NativeHeapFreeSize = "+ df.format(free) + "MB"  + " in [" + clazz.getName() + "]");
        Log.e("HeapLog", "debug.memory: allocated: " + df.format(new Double(Runtime.getRuntime().totalMemory()/1048576)) + "MB of " + df.format(new Double(Runtime.getRuntime().maxMemory()/1048576))+ "MB (" + df.format(new Double(Runtime.getRuntime().freeMemory()/1048576)) +"MB free)");
        Log.e("HeapLog", "");
        logNum++;       
	}
	
	public static boolean isLegalAndroidAccount(String andrAccount){
		boolean flag = false ;
		Pattern p = Pattern.compile("\\d{6,}"); 
		Matcher m = p.matcher(andrAccount) ;
		flag = m.matches() ;
		return flag ;
	}
	
	public static Bitmap drawableToBitmap(Drawable drawable)
	{

		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}
}
